<?php
/**
 * 日志封装
 * 文件操作(生成日志)支持多条插入 
 * (如果插入多条语句并换行  用','逗号分开) 
 * 
 * @author zlj <389843954@qq.com>
 */
namespace app\common\model;
class Logs {  

    /**
     * 写日志(专用于订单)
     * @param  [type] $content [内容]
     * @param  [type] $path    [路径]
     * @param  [type] $mode    [追加]
     * @return [type]          [description]
     */
    public function addOrderLog($content) {
        
        $path = 'uploads/wlogs/';
        //目录下文件数量
        $num = count(scandir($path))-2>0?count(scandir($path))-2:0;

        if($num){
            //有文件
            //如果查出上传数量,则清除超量文件,先搜索此文件夹下所有文件,并剔除key[0],key[1]
            $file=scandir($path);
            array_splice($file,0,2);
            $_n = array();
            // 获取文件创建时间并进行降序排序
            foreach ($file as $_k => $_v) {
                if($_v=="." || $_v==".."){
                    continue;
                }
                $_n[$_k] = filectime($path.$_v);
                $m[filectime($path.$_v)] = $_v;
            }
            sort($_n);
            //获取最新的文件路径
            $newpath =  $path.$m[$_n[$num-1]];
            //100M
            $fiel_size = 100*1024*1024;
            
            if(filesize($newpath)<$fiel_size){
                //小于100M 则继续写入
                $handle_file = $newpath;
            }else{
                //大于则新建文件,再写入
                $handle_file = $path.date('YmdHis',time()).'.txt';
            }
        }else{
            //第一次写入
             $handle_file = $path.date('YmdHis',time()).'.txt';
        }

        $content = $content."    ".date('Y-m-d H:i:s',time());
        $this->wLogs($handle_file,$content);

        return true;
    }

    /**
     * 写订单日志(加文件锁,避免同时锁住)
     * @return [type] [description]
     */
    public function wLogs($handle_file,$content){
                
        //加文件锁
        $fp = fopen($handle_file, "a" );
        //加锁
        if(flock ( $fp, LOCK_EX | LOCK_NB )){
            fwrite ( $fp, $content . "\r\n\r\n" );

            flock ( $fp, LOCK_UN );
            fclose ( $fp );

            return true;
        }else{
            //未进入锁
            fclose ( $fp );

            sleep(2);
            
            $this->wLogs($handle_file,$content);

            return true;
        }
    }

} 